/**
  @authoer: lss
  @date: 2021/3/5
  @note:
**/
package database

import (
	"errors"
	"github.com/astaxie/beego/logs"
	expiremap "github.com/nursik/go-expire-map"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"time"
	"wonlicsys/api/v1"
)

var (
	LicSysDbMap  *expiremap.ExpireMap
	licSysDbPool *gorm.DB
)

const licSysKey = "wonLicSys"

func GetDbWonLicGorm() (*gorm.DB, error) {
	defer func() {
		if err := recover(); err != nil {
			logs.Error(err, "错误--------->")
		}
	}()
	db, ok := LicSysDbMap.Get(licSysKey)
	if !ok || db == nil {
		mysqlHost := v1.Conf.DbHost
		mysqlUser := v1.Conf.DbUsername
		mysqlPass := v1.Conf.DbPassword
		mysqlCharset := v1.Conf.DbCharset
		mysqlDatabase := v1.Conf.DbDataBase
		mysqlPort := v1.Conf.DbPort
		var err error
		dsn := mysqlUser + ":" +
			mysqlPass + "@tcp(" +
			mysqlHost + ":" + mysqlPort + ")/" +
			mysqlDatabase + "?charset=" +
			mysqlCharset + "&parseTime=True&loc=Local"
		licSysDbPool, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
			SkipDefaultTransaction: true, //禁用默认事务
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true,
			},
		})
		if err != nil {
			logs.Error(err)
			return nil, err
		}
		sqlDB, err := licSysDbPool.DB()
		// SetMaxIdleConns 设置空闲连接池中连接的最大数量
		sqlDB.SetMaxIdleConns(10)
		// SetMaxOpenConns 设置打开数据库连接的最大数量。
		sqlDB.SetMaxOpenConns(100)

		sqlDB.SetConnMaxLifetime(time.Second * 600)

		LicSysDbMap.Set(licSysKey, licSysDbPool, time.Minute*30)
	} else {
		licSysDbPool, ok = db.(*gorm.DB)
		if !ok {
			return nil, errors.New("数据库连接失败")
		}
	}

	return licSysDbPool, nil
}

func CloseDbWonLicGorm(db *gorm.DB) {
	LicSysDbMap.SetTTL(licSysKey, time.Minute*30)

}
